<template>
  <el-card header="修改密码" style="width: 50%">
    <el-form ref="refForm" :model="formData" :rules="rules" label-position="right" :label-width="80">
      <el-form-item label="旧密码" prop="oldPwd">
        <el-input v-model="formData.oldPwd" type="password" autocomplete="off" show-password></el-input>
      </el-form-item>
      <el-form-item label="新密码" prop="newPwd">
        <el-input v-model="formData.newPwd" type="password" autocomplete="off" show-password></el-input>
      </el-form-item>
      <el-form-item label="确认密码" prop="checkPwd">
        <el-input v-model="formData.checkPwd" type="password" autocomplete="off" show-password></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :loading="saving" @click="handleSave">更新密码</el-button>
        <el-alert v-show="msg" :title="msg" type="success" show-icon style="margin-top: 15px" />
      </el-form-item>
    </el-form>
  </el-card>
</template>
<script setup lang="ts">
import { reactive, ref } from 'vue'
import { ElMessage, ElForm, ElFormItem, ElInput, ElCard, ElAlert } from 'element-plus'
import { userApi } from '@/api/modules/system/user'

const refForm = ref()
const formData = reactive<{ oldPwd: string; newPwd: string; checkPwd: string }>({
  oldPwd: '',
  newPwd: '',
  checkPwd: ''
})

const validateCheckPwd = (rule: any, value: string, callback: (err?: Error) => void) => {
  if (value === '') {
    callback(new Error('请再次输入新密码'))
  } else if (value !== formData.newPwd) {
    callback(new Error('两次输入密码不一致!'))
  } else {
    callback()
  }
}

const rules = {
  oldPwd: [{ required: true, message: '请输入旧密码', trigger: 'blur' }],
  newPwd: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    {
      pattern:
        /^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![a-z0-9]+$)(?![A-Z\W_]+$)(?![a-z\W_]+$)(?![0-9\W_]+$)[a-zA-Z0-9\W_]{8,16}$/,
      message: '密码为数字，小写字母，大写字母，特殊符号 至少包含三种，长度为8 - 16位'
    }
  ],
  checkPwd: [{ required: true, validator: validateCheckPwd }]
}

const msg = ref('')
const saving = ref(false)
const handleSave = () => {
  refForm.value.validate((valid: boolean) => {
    if (valid) {
      saving.value = true
      userApi.updateMyPwd(formData.oldPwd, formData.newPwd).then(resp => {
        saving.value = false
        if (resp.success) {
          refForm.value.resetFields()
          msg.value = '密码已经修改成功'
        } else {
          msg.value = ''
          ElMessage.error(resp.message)
        }
      })
    }
  })
}
</script>
